package com.zingrow.web.configure.domain.controller;

import java.io.File;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import com.idaycrm.idaybase.utils.JsonUtils;
import com.zingrow.common.ReturnStandardDataFormat;
import com.zingrow.common.utils.CommonUtils;
import com.zingrow.common.utils.EncodingUtils;
import com.zingrow.common.utils.ExcelUtils;
import com.zingrow.common.utils.OptClass;
import com.zingrow.common.utils.PageView;
import com.zingrow.web.base.CodeMsg;
import com.zingrow.web.base.controller.BaseController;
import com.zingrow.web.base.enums.Menu;
import com.zingrow.web.base.enums.Operation;
import com.zingrow.web.common.utils.AnalyzeResult;
import com.zingrow.web.configure.domain.model.Domain;
import com.zingrow.web.configure.domain.service.IDomainService;
import com.zingrow.web.support.operate.model.OptRecord;
import com.zingrow.web.support.operate.service.IOptRecordService;
import com.zingrow.web.user.model.ActiveUser;
import com.zingrow.web.user.model.UserPermission;
import com.zingrow.web.user.service.IPermissionService;

@Controller
@RequestMapping(value="/domain/",produces = "application/json;charset=UTF-8")
public class DomainController extends BaseController {
	@Autowired
	private IDomainService domainService;
	@Autowired
	private IOptRecordService optRecordService;
	@Autowired
	private IPermissionService permissionService;
	@Autowired
	private IOptRecordService ioptRecordService;
	@Autowired
	private IDomainService idomainService;
	//模糊查询
	@ResponseBody
	@RequestMapping("queryByParams")
	public String queryByParams(HttpServletRequest request,HttpServletResponse response,Integer pageIndex,
			Integer pageSize,String domain_domain,String domain_name,String domain_category,Integer is_exprot) {
		List<Domain> list = new ArrayList<Domain>();
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR,CodeMsg.MSG_ERROR,list);
		PageView pageView = null;
		try {
			//设置分页
			if (pageIndex == null || pageIndex <= 0) {
				pageIndex = 1;
			}
			if (pageSize == null || pageSize <= 0) {
				pageSize = 10;
			}
			//把设置的分页值放进pageView中
			pageView = new PageView(pageSize,pageIndex);
			//字符转换
			if (domain_domain != null || "".equals(domain_domain)) {
				//转码后还是放进要转码的这个字段中
				domain_domain = EncodingUtils.fixUrlParamEncoding(request, domain_domain);
			}
			if (domain_name != null || "".equals(domain_name)) {
				domain_name = EncodingUtils.fixUrlParamEncoding(request, domain_name);
			}
			if (domain_category != null || "".equals(domain_category)) {
				domain_category = EncodingUtils.fixUrlParamEncoding(request, domain_category);
			}
			// 这的pageView 设置为NULL 是为了下拉列表查询到所有所属站点，而不是10条
			list = domainService.queryByParams(pageView, domain_domain, domain_name, domain_category, is_exprot);
				//新增一条操作记录
				ActiveUser opuser = getUser(request);//获取操作用户
				OptRecord s = new OptClass().zd_query(opuser,Menu.Resourceallocation.toString(),
						Menu.domain.toString(),Operation.query.toString(),domain_name,domain_domain,domain_category);
				if(!s.getOptName().equals("null"))	
				ioptRecordService.insert(s);
		} catch (Exception e) {
			log.error("根据参数查询异常");
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"站点配置根据参数查询异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
			standardData.setReturnData(list);
		}
		standardData.setReturnData(list);
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage(CodeMsg.MSG_OK);
		standardData.setTotalPages(pageView.getPageCount());
		standardData.setTotalRecords(pageView.getRowCount());
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}
	//删除方法
	@ResponseBody
	@RequestMapping("deletedomain")
	public String deletedomain(HttpServletRequest request,HttpServletResponse response,Integer domain_id,String domain_name) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR,CodeMsg.MSG_ERROR,null);
		try {
			//判断参数的合法性
			if (CommonUtils.isObjectNull(domain_id)) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			//字符转换
			if (CommonUtils.isStrNotNull(domain_name)) {
				domain_name = EncodingUtils.fixUrlParamEncoding(request, domain_name);
			}
			if (domainService.deletedomain(domain_id)) {
				//操作记录
				ActiveUser opuser = getUser(request);//获取操作用户
				OptRecord s = new OptClass().zd_delete(opuser,Menu.Resourceallocation.toString(),
						Menu.domain.toString(),Operation.delete.toString(),domain_name);
				ioptRecordService.insert(s);	
				//操作成功
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage(CodeMsg.MSG_OK);
			} else {
				ActiveUser opuser = getUser(request);//获取操作用户
				OptRecord s = new OptClass().recordabnormality(opuser,"站点配置删除失败");
				ioptRecordService.insert(s);
				standardData.setReturnCode(CodeMsg.CODE_ERROR);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR);
			}
		} catch (Exception e) {
			log.error("根据参数删除异常");
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"站点配置删除异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
		}
		return JsonUtils.toString(standardData,"yyyy-MM-dd HH:mm:ss");
	}
	//新增
	@ResponseBody
	@RequestMapping("addDomain")
	public String addDomain(HttpServletRequest request,HttpServletResponse response,Domain domain) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR,CodeMsg.MSG_ERROR,null);
		try {
			//判断参数是否正确
			if(CommonUtils.isStrNull(domain.getDomain_category())||CommonUtils.isStrNull(domain.getDomain_domain())||
				CommonUtils.isStrNull(domain.getDomain_name())) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			} else {
				//传入参数转码
				domain.setDomain_category(EncodingUtils.fixUrlParamEncoding(request, domain.getDomain_category()));
				domain.setDomain_domain(EncodingUtils.fixUrlParamEncoding(request, domain.getDomain_domain()));
				domain.setDomain_name(EncodingUtils.fixUrlParamEncoding(request, domain.getDomain_name()));
			}
			//判断站点名称和站点网址
			if (domainService.queryByDomainAndName(null,domain.getDomain_domain(),domain.getDomain_name())) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_OTHER);
				standardData.setReturnMessage("站点名称或站点网址已存在，请重新填写");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			if (domainService.addDomain(domain)) {
				//操作记录
				ActiveUser opuser = getUser(request);//获取操作用户
				OptRecord s = new OptClass().zd_add(opuser,Menu.Resourceallocation.toString(),
						Menu.domain.toString(),Operation.insert.toString(),domain);
				ioptRecordService.insert(s);	
				//新增成功
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage(CodeMsg.MSG_OK);
			} else {
				ActiveUser opuser = getUser(request);//获取操作用户
				OptRecord s = new OptClass().recordabnormality(opuser,"站点配置新增失败");
				ioptRecordService.insert(s);
				standardData.setReturnCode(CodeMsg.CODE_ERROR);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR);
			}
		} catch (Exception e) {
			log.error("新增站点配置异常");
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"站点配置新增异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}
	//查询单个数据
	@ResponseBody
	@RequestMapping("queryByid")
	public String queryByid(HttpServletRequest request,HttpServletResponse response,Integer domain_id) {
		Domain domain = new Domain();
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR,CodeMsg.MSG_ERROR,null);
		try {
			//判断参数合法性
			if (CommonUtils.isObjectNull(domain_id)) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			domain = domainService.queryByid(domain_id);			
		} catch (Exception e) {
			log.error("根据编号查询异常");
			log.error(e.getMessage());
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
			standardData.setReturnData(domain);
		}
		standardData.setReturnData(domain);
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage(CodeMsg.MSG_OK);
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}
	
	//修改
	@ResponseBody
	@RequestMapping("modifyDomain")
	public String modifyDomain(HttpServletRequest request,HttpServletResponse response,Domain domain) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR,CodeMsg.MSG_ERROR,null);
		try {
			//判断参数是否正确
			if (CommonUtils.isStrNull(domain.getDomain_category())||CommonUtils.isStrNull(domain.getDomain_domain())||
					CommonUtils.isStrNull(domain.getDomain_name())) {
				
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			} else {
				//转码
				domain.setDomain_category(EncodingUtils.fixUrlParamEncoding(request, domain.getDomain_category()));
				domain.setDomain_domain(EncodingUtils.fixUrlParamEncoding(request, domain.getDomain_domain()));
				domain.setDomain_name(EncodingUtils.fixUrlParamEncoding(request, domain.getDomain_name()));
			}
			//判断站点名称和站点网址
			if (domainService.queryByDomainAndName(domain.getDomain_id(),domain.getDomain_domain(),domain.getDomain_name())) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_OTHER);
				standardData.setReturnMessage("站点名称或站点网址已存在，请重新填写");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			Domain ydomain=idomainService.queryByid(domain.getDomain_id());
			if (domainService.modifyDomain(domain)) {
				//操作记录
				ActiveUser opuser = getUser(request);//获取操作用户
				OptRecord s = new OptClass().zd_updata(opuser,Menu.Resourceallocation.toString(),
						Menu.domain.toString(),Operation.update.toString(),ydomain,domain);
				ioptRecordService.insert(s);	
				//操作成功
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage(CodeMsg.MSG_OK);
			} else {
				standardData.setReturnCode(CodeMsg.CODE_ERROR);
				standardData.setReturnMessage(CodeMsg.MSG_OK);
			}
		} catch (Exception e) {
			log.error("站点配置修改异常");
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"站点配置修改站点异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}
	//根据名字模糊查询频道所用接口
	@ResponseBody
	@RequestMapping("queryParamsByName")
	public String queryParamsByName(HttpServletRequest request,HttpServletResponse response,String domain_name) {
		List<Domain> list = new ArrayList<Domain>();
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR,CodeMsg.MSG_ERROR,list);
		try {
			//字符转换
			if (domain_name != null || "".equals(domain_name)) {
				domain_name = EncodingUtils.fixUrlParamEncoding(request, domain_name);
			}
			list = domainService.queryParamsByName(domain_name);
		} catch (Exception e) {
			log.error("根据参数查询异常");
			log.error(e.getMessage());
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
			standardData.setReturnData(list);
		}
		standardData.setReturnData(list);
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage(CodeMsg.MSG_OK);
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}
	//导出模板
	@ResponseBody
	@RequestMapping("exportExcelForModel")
	public String exportExcelForModel(HttpServletRequest request,HttpServletResponse response) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR,CodeMsg.MSG_ERROR,null);
		List<Domain> list = new ArrayList<Domain>();
		try {
			//表头
			List<String> titls = Arrays.asList("站点类型","站点网址","站点名称");
			//表字段名称
			List<String> paramsName = Arrays.asList("domain_category","domain_domain",
					"domain_name");
			OutputStream out = null;
			try {
				//获取输出流
				out = response.getOutputStream();
				//清空流
				response.reset();
				//定义响应输出类型
				response.setContentType("application/msexcel");
				//定义输出文件头
				response.setHeader("Content-disposition", 
						"attachment; filename=" + new String("站点配置模版".getBytes("GBK"), "iso8859-1") + ".xls");
				ExcelUtils.exportExcel(titls, paramsName, list, out);
			} catch (Exception e) {
				log.error(e.getMessage());
			} finally {
				out.close();
			}
				ActiveUser opuser = getUser(request);//获取操作用户
				OptRecord s = new OptClass().modelxz(opuser,Menu.Resourceallocation.toString(),
						Menu.domain.toString(),Operation.modelxz.toString(),"导入模板下载");
				ioptRecordService.insert(s);	
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	//导入
	@ResponseBody
	@RequestMapping("importExcelModel")
	public String importExcelModel(HttpServletRequest request,HttpServletResponse response) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR,CodeMsg.MSG_ERROR,null);
		//获取Web项目的全路径                             
		String realPath = request.getSession().getServletContext().getRealPath("/uploadTemp/");
		File saveFile = null;
		//如果目录不存在就创建
		if (!new File(realPath).exists()) {
			new File(realPath).mkdir();
		}
		saveFile = new File(new File(realPath),
				getUser(request).getUserAccount() + System.currentTimeMillis() + "domain_temp.xls");
		//把request转型
		DefaultMultipartHttpServletRequest multipartRequest = (DefaultMultipartHttpServletRequest)request;
		//获得文件
		MultipartFile multipartFile = multipartRequest.getFile("importExcel");
		//保存解析出来的信息
		AnalyzeResult<Domain> analyzeResult = new AnalyzeResult<Domain>(true,"",new ArrayList<Domain>());
		//接收导入失败的数据，成功此list的size为0，否则里面的数据为错误数据
		List<Integer> errorIndexList = new ArrayList<Integer>();
		try {
			//转换成file
			multipartFile.transferTo(saveFile);
			//进行数据检测,将数据写入analyzeResult.list中
			domainService.analyzeExcelData(saveFile, analyzeResult);
			if (analyzeResult.isSuccess()) {
				List<Domain> list = analyzeResult.getList();
				//循环判断是否重复
				for (Domain domain : list) {
					if (domainService.queryByDomainAndName(null,domain.getDomain_domain(),domain.getDomain_name())) {
						standardData.setReturnCode(CodeMsg.CODE_ERROR_OTHER);
						standardData.setReturnMessage("Excel中站点URL或站点名有重复值");
						return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
					}
				}
				//通过判断重复值，执行新增
				for (Domain domain : list) {
					domainService.addDomain(domain);
				}
				if (errorIndexList.size() == 0) {
					ActiveUser opuser = getUser(request);//获取操作用户
					OptRecord s = new OptClass().goiss(opuser,Menu.Resourceallocation.toString(),
							Menu.domain.toString(),Operation.daoru.toString(),list.size());
					ioptRecordService.insert(s);	
					//导入数据成功
					standardData.setReturnCode(CodeMsg.CODE_OK);
					standardData.setReturnMessage(CodeMsg.MSG_OK);
				} else {
					//有导入错误返回错误行数
					ActiveUser opuser = getUser(request);//获取操作用户
					OptRecord s = new OptClass().goiss(opuser,Menu.Resourceallocation.toString(),
							Menu.domain.toString(),Operation.daoru.toString(),list.size()-errorIndexList.size());
					ioptRecordService.insert(s);	
					standardData.setReturnCode(CodeMsg.CODE_ERROR_SAME);
					standardData.setReturnMessage("导入数据完成，存在部分数据导入失败："+errorIndexList.size());
				}
			} else {
				//检测数据失败，返回相应提示信息
				standardData.setReturnCode(CodeMsg.CODE_ERROR_OTHER);
				standardData.setReturnMessage("检测数据格式错误："+analyzeResult.getErrorMessage());
			}	
		} catch (Exception e) {
			log.error("导入站点信息异常");
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"站点配置导入频道信息异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_ERROR);
			standardData.setReturnMessage(CodeMsg.MSG_ERROR);
		} finally {
			//结束后删除本地文件
			saveFile.delete();
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}
	//导出数据
	@ResponseBody
	@RequestMapping("exportExcelForPageData")
	public String exportExcelForPageData(HttpServletRequest request,HttpServletResponse response,String domain_id){
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR,CodeMsg.MSG_ERROR,null);
		try {
			//定义表头
			List<String> titls = Arrays.asList("站点id","标签值","站点类型","站点","站点名称","站点描述","站点状态");
			//定义表的字段名
			List<String> paramsName = Arrays.asList("domain_id","tagvalue_id","domain_category","domain_domain",
					"domain_name","domain_sign","is_deletes");
			//处理传入的id，并查询出列表
			List<Integer> idlist = new ArrayList<>();
			List<Domain> domain = null;
			if (StringUtils.isNoneBlank(domain_id)) {
				//分割id
				for (String strids : domain_id.split(",")) {
					idlist.add(Integer.valueOf(strids));
				}
				domain = domainService.queryDomainById(idlist);	
			}
			//定义一个输出流
			OutputStream out = null;
			try {
				//获取输出流
				out = response.getOutputStream();
				//清空流
				response.reset();
				//定义响应输出类型
				response.setContentType("application/msexcel");
				//设置输出文件头
				response.setHeader("Content-disposition",
                        "attachment; filename=" + new String("站点信息".getBytes("GBK"), "iso8859-1") + ".xls");
				ExcelUtils.exportExcel(titls, paramsName, domain, out);
			} catch (Exception e) {
				log.error(e.getMessage());
				e.printStackTrace();
			} finally {
				//关闭流
				out.close();
			}
			//新增一条操作记录
			//操作日志
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().goiss(opuser,Menu.Resourceallocation.toString(),
					Menu.domain.toString(),Operation.daochu.toString(),idlist.size());
			ioptRecordService.insert(s);	
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}
}
